const { Controller } = require("egg");

const { getReqParams, getResBody, getResList, getPageParams, needParam, typeOf, consoleLog } = require("../../utils");
const validRules = require("../../utils/valid/rules");
const { getInsertRows } = require("../../scripts/note/core/creator/mysql/_utils");

const insertCodeMap = {
  0: "成功",
  1: "已存在",
  // 2: "已删除",
  99: "未知错误",
};

module.exports = class CommonController extends Controller {
  // 新增
  async insert() {
    const { ctx, service } = this;
    const rules = {};
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { tableName, addParams } = ctx;
    let rows = [];
    const t = typeOf(params);
    if (t === "Object") {
      rows = getInsertRows(tableName, params);
    } else if (t === "Array") {
      if (rows.length < 2 || !Array.isArray(rows[0])) throw new Error(`要插入的rows应为一个二维数组，实为：${JSON.stringify(rows)}`);
      rows = params;
    } else {
      throw new Error(`暂未处理此类型：${t}`);
    }
    const isFind = rows[0].find(it => it === "create_id");
    if (!isFind) {
      rows[0].push("create_id");
      rows.slice(1).forEach(row => {
        const userId = service.user.getUserId();
        row.push(userId);
      });
    }
    const resCode = await service.common.insert(tableName, rows);
    ctx.body = getResBody({ msg: insertCodeMap[resCode] });
  }
  // 删除
  async delete() {
    const { ctx, service } = this;
    const rules = { id: validRules.id };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { tableName, addParams } = ctx;
    const resCode = await service.common.delete(tableName, params);
    ctx.body = getResBody({ msg: insertCodeMap[resCode] });
  }
  // 更改
  async update() {
    const { ctx, service } = this;
    const rules = { id: validRules.id };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { id, ...fields } = params;
    const fieldsKeys = Object.keys(fields);
    const isFind = fieldsKeys.find(it => it === "update_id");
    if (!isFind) {
      fields.update_id = service.user.getUserId();
    }
    const { tableName, addParams } = ctx;
    const resCode = await service.common.update(tableName, fields, { where: { id } });
    ctx.body = getResBody({ msg: insertCodeMap[resCode] });
  }
  // 查列表
  async list() {
    const { ctx, service } = this;
    const rules = {};
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { tableName, addParams } = ctx;
    const pageParams = getPageParams(params, tableName, addParams);
    const data = await service.common.list(tableName, pageParams);
    const { whereParams } = pageParams;
    const total = await service.common.countTotal(tableName, { where: whereParams });
    ctx.body = getResBody({ data: getResList(data, total, pageParams.limits) });
  }
  // 查详情（只有一条记录，返回对象）
  async detail() {
    const { ctx, service } = this;
    const rules = { id: validRules.id };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { tableName, addParams } = ctx;
    const data = await service.common.detail(tableName, { where: params });
    ctx.body = getResBody({ data });
  }
  // 查记录（可能多条记录，返回数组）
  async find() {
    const { ctx, service } = this;
    const rules = { id: validRules.id };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { tableName, addParams } = ctx;
    const data = await service.common.find(tableName, params);
    ctx.body = getResBody({ data });
  }
  // 总数增加或减少
  async countUpdate() {
    const { ctx, service } = this;
    const rules = { id: validRules.id };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { tableName, addParams } = ctx;
    const { id, step, ...restParams } = params;
    const fields = Object.keys(restParams);
    const data = await service.common.countUpdate(tableName, fields, { where: { id } }, step);
    ctx.body = getResBody({ data });
  }
  // 切换操作状态
  async operateToggle() {
    const { ctx, service } = this;
    const rules = { id: validRules.id };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { tableName, addParams } = ctx;
    // type: 12(点赞), 13(点踩), ....
    const { id, step = 1, type = 12, update_fields } = params;
    const data = await service.common.countUpdate(tableName, update_fields, { where: { id } }, step);
    // const result = await service.common.update("operate_status", { status: "NOT status" }, { where: { create_id: id, type } });
    const result = await service.common.insertOrUpdate(
      "operate_status",
      [
        ["create_id", "type", "status"],
        [id, type, 1],
      ],
      { status: "NOT status" }
    );
    ctx.body = getResBody({ data });
  }
};
